/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ez2find.backing;

import com.ez2find.manager.AreaManagerLocal;
import com.ez2find.manager.EventCategorieManagerLocal;
import com.ez2find.manager.EventManagerLocal;
import com.ez2find.manager.LocationManagerLocal;
import com.ez2find.manager.RegisterUserManagerLocal;
import com.ez2find.model.Area;
import com.ez2find.model.Event;
import com.ez2find.model.EventCategorie;
import com.ez2find.model.Location;
import com.ez2find.model.RegisterUser;
import com.ez2find.services.EmailLocal;
import com.ez2find.util.RequestContext;
import com.ez2find.util.SessionContext;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Administrador
 */
public class EventBean {

    @EJB
    private EventManagerLocal ejbEventManager;
    @EJB
    private EventCategorieManagerLocal ejbEventCategorieManager;
    @EJB
    private RegisterUserManagerLocal ejbUserManager;
    @EJB
    private EmailLocal ejbEmail;
    @EJB
    private AreaManagerLocal ejbAreaManager;
    @EJB
    private LocationManagerLocal ejbLocationManager;
    private Event event;
    private int back;
    private long eventCategorieId;
    private long areaId;
    private String email1;
    private boolean linkRPOk;
    private boolean createOk;
    private boolean maskedEmail;
    private int page;
    private String searchValue;
    private Date searchDate;
    private boolean searchForDate;
    private boolean onlySearchTitles;
    private boolean hasImage;

    public Event getEvent() {
        if (event == null) {
            ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
            HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
            HttpSession session = request.getSession();
            if (session.isNew()) {
                try {
                    String errorPageURL = externalContext.getRequestContextPath() + "/faces/welcome.jsp";
                    externalContext.redirect(errorPageURL);
                    FacesMessage msg = new FacesMessage("The session has bean expired");
                    msg.setSeverity(FacesMessage.SEVERITY_ERROR);
                    FacesContext.getCurrentInstance().addMessage(null, msg);
                    return null;
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                    return null;
                }
            } else {
                SessionBean sessionBean = (SessionBean) SessionContext.getAttribute("sessionBean");
                if (sessionBean.getEjbSession().getEvent() != null) {
                    event = sessionBean.getEjbSession().getEvent();
                    if(event.getTypeReplyTo().equals("masked email"))
                        maskedEmail=true;
                    areaId = 0;
                    if (event.getArea() != null) {
                        areaId = event.getArea().getId();
                    }
                    eventCategorieId = event.getEventCategorie().getId();
                } else {
                    event = new Event();
                    event.setTypeReplyTo("masked email");
                    event.setStartDate(new Date(System.currentTimeMillis()));
                    event.setOnlyOneDate(true);
                    event.setEndDate(new Date(System.currentTimeMillis()));
                    if (!sessionBean.getAreasCurrentSite().isEmpty()) {
                        if (sessionBean.getEjbSession().getCurrentArea() != null) {
                            areaId = sessionBean.getEjbSession().getCurrentArea().getId();
                        } else {
                            areaId = sessionBean.getEjbSession().getCurrentSite().getAreas().get(1).getId();
                        }
                    }
                    try {
                        PostBean postBean = (PostBean) RequestContext.getAttribute("postBean");
                        back = postBean.getBack();
                    } catch (Exception ex) {
                    }
                }
            }
        }
        return event;
    }

    public void setEvent(Event event) {
        this.event = event;
    }

    public List<Event> getlistAll() {
        return ejbEventManager.listAll();
    }

    public String create() {
        ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
        HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
        HttpSession session = request.getSession();
        if (session.isNew()) {
            try {
                String errorPageURL = externalContext.getRequestContextPath() + "/faces/eventPosting/create.jsp";
                externalContext.redirect(errorPageURL);
                FacesMessage msg = new FacesMessage("The session has bean expired");
                msg.setSeverity(FacesMessage.SEVERITY_ERROR);
                FacesContext.getCurrentInstance().addMessage(null, msg);
                return null;
            } catch (IOException ioe) {
                ioe.printStackTrace();
                return null;
            }
        } else {
            try {
                SessionBean sessionBean = (SessionBean) SessionContext.getAttribute("sessionBean");
                if (sessionBean.getEjbSession().getOwner() != null) {
                    if (!event.getOnlyOneDate() && (event.getStartDate().after(new Date(System.currentTimeMillis())) || event.getStartDate().after(event.getEndDate()) || (event.getStartDate().getTime()+1296000000)<event.getEndDate().getTime())) {
                        FacesMessage msg = new FacesMessage("The dates are invalid, Maximum event length is 15 days");
                        msg.setSeverity(FacesMessage.SEVERITY_ERROR);
                        FacesContext.getCurrentInstance().addMessage(null, msg);
                        return null;
                    }
                    event.setCode((ejbEventManager.lastCode()) + 1);
                    event.setType("event");
                    event.setUser(sessionBean.getEjbSession().getOwner());
                    event.setEmail(sessionBean.getEjbSession().getOwner().getEmail());
                    if(event.getTypeReplyTo().equals("masked email"))
                        ejbEmail.addAnonymousEmail("event", event.getCode(), event.getEmail());
                    event.setPublishDate(new Date(System.currentTimeMillis()));
                    event.setStatus("active");
                    event.setCreateDate(new Date(System.currentTimeMillis()));
                    event.setSite(sessionBean.getEjbSession().getCurrentSite());
                    if (areaId != 0) {
                        event.setArea(ejbAreaManager.find(areaId));
                    }
                    EventCategorie eventCategorie = ejbEventCategorieManager.find(eventCategorieId);
                    event.setEventCategorie(eventCategorie);
                    event.setCategorie(eventCategorie.getCategorie());
                    if(event.getOnlyOneDate())
                        event.setEndDate(event.getStartDate());
                    ejbEventManager.create(event);
                    FacesMessage msg = new FacesMessage("Your post has been successfully registered.");
                    FacesContext.getCurrentInstance().addMessage(null, msg);
                    FacesMessage msg1 = new FacesMessage("To manage your post,  log into your account.");
                    FacesContext.getCurrentInstance().addMessage(null, msg1);
                    createOk = true;
                    return "success";
                } else {
                    if ((event.getEmail().length() < 4) || !event.getEmail().contains("@") || !event.getEmail().contains(".") || (email1.length() < 4) || !email1.contains("@") || !email1.contains(".") || !event.getEmail().equals(email1)) {
                        FacesMessage msg = new FacesMessage("The emails address don't equals or invalids");
                        msg.setSeverity(FacesMessage.SEVERITY_ERROR);
                        FacesContext.getCurrentInstance().addMessage(null, msg);
                        return null;
                    }
                    if (!event.getOnlyOneDate() && (event.getStartDate().after(new Date(System.currentTimeMillis())) || event.getStartDate().after(event.getEndDate()) || (event.getStartDate().getTime()+1296000000)<event.getEndDate().getTime())) {
                        FacesMessage msg = new FacesMessage("The dates are invalid, Maximum event length is 15 days");
                        msg.setSeverity(FacesMessage.SEVERITY_ERROR);
                        FacesContext.getCurrentInstance().addMessage(null, msg);
                        return null;
                    }
                    RegisterUser userAccount = ejbUserManager.findUserByEmail(event.getEmail());
                    if (userAccount != null) {
                        if (userAccount.getStatus().equals("active") || userAccount.getStatus().equals("reactive")) {
                            event.setUser(userAccount);
                            event.setCode((ejbEventManager.lastCode()) + 1);
                            event.setType("event");
                            event.setStatus("pending");
                            event.setCreateDate(new Date(System.currentTimeMillis()));
                            event.setSite(sessionBean.getEjbSession().getCurrentSite());
                            if (areaId != 0) {
                                event.setArea(ejbAreaManager.find(areaId));
                            }
                            EventCategorie eventCategorie = ejbEventCategorieManager.find(eventCategorieId);
                            event.setEventCategorie(eventCategorie);
                            event.setCategorie(eventCategorie.getCategorie());
                            if(event.getOnlyOneDate())
                                event.setEndDate(event.getStartDate());
                            ejbEventManager.create(event);
                            FacesMessage msg = new FacesMessage("Your post has been successfully registered.");
                            FacesContext.getCurrentInstance().addMessage(null, msg);
                            FacesMessage msg1 = new FacesMessage("The User Account from this email " + userAccount.getEmail() + " exist.");
                            FacesContext.getCurrentInstance().addMessage(null, msg1);
                            FacesMessage msg2 = new FacesMessage("If you forgot your password or need to reactive your account clik in the link to recovery password.");
                            FacesContext.getCurrentInstance().addMessage(null, msg2);
                            FacesMessage msg3 = new FacesMessage("Please enter in your account and published your posting.");
                            FacesContext.getCurrentInstance().addMessage(null, msg3);
                            linkRPOk = true;
                            createOk = true;
                            return "success";
                        }
                        //userAccount.setDefaultSite(sessionBean.getEjbSession().getCurrentSite());
                        userAccount.setRegisterDate(new Date(System.currentTimeMillis()));
                        Random r = new Random();
                        String token = Long.toString(Math.abs(r.nextLong()), 36);
                        userAccount.setConfirmationCode(token);
                        ejbUserManager.update(userAccount, false);
                        ejbEmail.sendAccountConfirmation(userAccount);
                        event.setUser(userAccount);
                    } else {
                        RegisterUser registerUser = new RegisterUser();
                        registerUser.setEmail(event.getEmail());
                        //registerUser.setDefaultSite(sessionBean.getEjbSession().getCurrentSite());
                        registerUser.setNumberOfPostings(50);
                        registerUser.setRegisterDate(new Date(System.currentTimeMillis()));
                        registerUser.setStatus("pending");
                        Random r = new Random();
                        String token = Long.toString(Math.abs(r.nextLong()), 36);
                        registerUser.setConfirmationCode(token);
                        ejbUserManager.create(registerUser);
                        RegisterUser newRegisterUser = ejbUserManager.merge(registerUser);
                        ejbEmail.sendAccountConfirmation(newRegisterUser);
                        event.setUser(newRegisterUser);
                    }
                    event.setCode((ejbEventManager.lastCode()) + 1);
                    event.setType("event");
                    event.setStatus("pending");
                    event.setCreateDate(new Date(System.currentTimeMillis()));
                    event.setSite(sessionBean.getEjbSession().getCurrentSite());
                    if (areaId != 0) {
                        event.setArea(ejbAreaManager.find(areaId));
                    }
                    EventCategorie eventCategorie = ejbEventCategorieManager.find(eventCategorieId);
                    event.setEventCategorie(eventCategorie);
                    event.setCategorie(eventCategorie.getCategorie());
                    if(event.getOnlyOneDate())
                        event.setEndDate(event.getStartDate());
                    ejbEventManager.create(event);
                    FacesMessage msg = new FacesMessage("Your post has been successfully registered.");
                    FacesContext.getCurrentInstance().addMessage(null, msg);
                    FacesMessage msg1 = new FacesMessage("For Administrate your Post eez2find creates an Account for you using the email address " + event.getEmail() + " to reply this post.");
                    FacesContext.getCurrentInstance().addMessage(null, msg1);
                    FacesMessage msg2 = new FacesMessage("Please active your account from email received and published your posting.");
                    FacesContext.getCurrentInstance().addMessage(null, msg2);
                    createOk = true;
                    return "success";
                }
            } catch (Exception ex) {
                ex.printStackTrace();
                FacesMessage msg = new FacesMessage("Error your Post can't register, maybe the email could not be sent or it doesn't exist");
                msg.setSeverity(FacesMessage.SEVERITY_ERROR);
                FacesContext.getCurrentInstance().addMessage(null, msg);
                return null;
            }
        }
    }

    public String previewCreate() {
        ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
        HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
        HttpSession session = request.getSession();
        if (session.isNew()) {
            try {
                String errorPageURL = externalContext.getRequestContextPath() + "/faces/eventPosting/create.jsp";
                externalContext.redirect(errorPageURL);
                FacesMessage msg = new FacesMessage("The session has bean expired");
                msg.setSeverity(FacesMessage.SEVERITY_ERROR);
                FacesContext.getCurrentInstance().addMessage(null, msg);
                return null;
            } catch (IOException ioe) {
                ioe.printStackTrace();
                return null;
            }
        } else {
            SessionBean sessionBean = (SessionBean) SessionContext.getAttribute("sessionBean");
            if (sessionBean.getEjbSession().getOwner() != null) {
                if (!event.getOnlyOneDate() && (event.getStartDate().after(new Date(System.currentTimeMillis())) || event.getStartDate().after(event.getEndDate()) || (event.getStartDate().getTime()+1296000000)<event.getEndDate().getTime())) {
                        FacesMessage msg = new FacesMessage("The dates are invalid, Maximum event length is 15 days");
                        msg.setSeverity(FacesMessage.SEVERITY_ERROR);
                        FacesContext.getCurrentInstance().addMessage(null, msg);
                        return null;
                    }
                event.setEmail(sessionBean.getEjbSession().getOwner().getEmail());
                return "success";
            } else {
                if ((event.getEmail().length() < 4) || !event.getEmail().contains("@") || !event.getEmail().contains(".") || (email1.length() < 4) || !email1.contains("@") || !email1.contains(".") || !event.getEmail().equals(email1)) {
                    FacesMessage msg = new FacesMessage("The emails address don't equals or invalids");
                    msg.setSeverity(FacesMessage.SEVERITY_ERROR);
                    FacesContext.getCurrentInstance().addMessage(null, msg);
                    return null;
                }
                if (!event.getOnlyOneDate() && (event.getStartDate().after(new Date(System.currentTimeMillis())) || event.getStartDate().after(event.getEndDate()) || (event.getStartDate().getTime()+1296000000)<event.getEndDate().getTime())) {
                        FacesMessage msg = new FacesMessage("The dates are invalid, Maximum event length is 15 days");
                        msg.setSeverity(FacesMessage.SEVERITY_ERROR);
                        FacesContext.getCurrentInstance().addMessage(null, msg);
                        return null;
                    }
                return "success";
            }
        }
    }

    public String update() {
        ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
        HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
        HttpSession session = request.getSession();
        if (session.isNew()) {
            try {
                String errorPageURL = externalContext.getRequestContextPath() + "/faces/welcome.jsp";
                externalContext.redirect(errorPageURL);
                FacesMessage msg = new FacesMessage("The session has bean expired");
                msg.setSeverity(FacesMessage.SEVERITY_ERROR);
                FacesContext.getCurrentInstance().addMessage(null, msg);
                return null;
            } catch (IOException ioe) {
                ioe.printStackTrace();
                return null;
            }
        } else {
            try {
                SessionBean sessionBean = (SessionBean) SessionContext.getAttribute("sessionBean");
                if(event.getTypeReplyTo().equals("masked email") && !maskedEmail)
                    ejbEmail.addAnonymousEmail("event", event.getCode(), event.getEmail());
                if(!event.getTypeReplyTo().equals("masked email") && maskedEmail)
                    ejbEmail.deleteAnonymousEmail("event", event.getCode(), event.getEmail());
                if (areaId != 0) {
                    event.setArea(ejbAreaManager.find(areaId));
                } else {
                    event.setArea(null);
                }
                EventCategorie eventCategorie = ejbEventCategorieManager.find(eventCategorieId);
                event.setEventCategorie(eventCategorie);
                event.setCategorie(eventCategorie.getCategorie());
                ejbEventManager.update(event);
                FacesMessage msg = new FacesMessage("Successful edit your Post");
                FacesContext.getCurrentInstance().addMessage(null, msg);
                sessionBean.getEjbSession().setEvent(null);
                SessionContext.removeAttribute("eventBean");
                return "success";
            } catch (Exception ex) {
                ex.printStackTrace();
                FacesMessage msg = new FacesMessage("Error your Post can't edit");
                msg.setSeverity(FacesMessage.SEVERITY_ERROR);
                FacesContext.getCurrentInstance().addMessage(null, msg);
                return null;
            }
        }
    }

    public long getAreaId() {
        return areaId;
    }

    public void setAreaId(long areaId) {
        this.areaId = areaId;
    }

    public Area getArea() {
        return ejbAreaManager.find(areaId);
    }

    public List<Location> getLocationsEventArea() {
        try {
            return ejbLocationManager.locationsArea(ejbAreaManager.find(areaId));
        } catch (Exception ex) {
            return new ArrayList<Location>();
        }
    }

    public boolean isCreateOk() {
        return createOk;
    }

    public void setCreateOk(boolean createOk) {
        this.createOk = createOk;
    }

    public boolean isLinkRPOk() {
        return linkRPOk;
    }

    public void setLinkRPOk(boolean linkRPOk) {
        this.linkRPOk = linkRPOk;
    }

    public String homeUser() {
        SessionContext.removeAttribute("eventBean");
        return "homeUser";
    }

    public int getBack() {
        return back;
    }

    public void setBack(int back) {
        this.back = back;
    }

    public long getEventCategorieId() {
        if (eventCategorieId == 0) {
            try {
                PostBean postBean = (PostBean) RequestContext.getAttribute("postBean");
                eventCategorieId = postBean.getCategorieId();
            } catch (Exception ex) {
            }
        }
        return eventCategorieId;
    }

    public void setEventCategorieId(long eventCategorieId) {
        this.eventCategorieId = eventCategorieId;
    }

    public List<Event> getListEvents() {
        ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
        HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
        HttpSession session = request.getSession();
        if (session.isNew()) {
            try {
                String errorPageURL = externalContext.getRequestContextPath() + "/faces/eventPosting/list.jsp";
                externalContext.redirect(errorPageURL);
                FacesMessage msg = new FacesMessage("The session has bean expired");
                msg.setSeverity(FacesMessage.SEVERITY_ERROR);
                FacesContext.getCurrentInstance().addMessage(null, msg);
                return null;
            } catch (IOException ioe) {
                ioe.printStackTrace();
                return null;
            }
        } else {
            String consult = "";
            boolean eventC = false;
            if (eventCategorieId > 0) {
                consult = consult + " AND e.eventCategorie=:eventCategorie";
                eventC = true;
            }
            if (searchForDate == true) {
                consult = consult + " AND e.startDate<=:startDate AND e.endDate>=:endDate";
            }
            if (hasImage) {
                consult = consult + " AND e.description like '%<img src=%'";
            }
            if (searchValue != null && !searchValue.equals("")) {
                if (onlySearchTitles) {
                    consult = consult + " AND e.title like '%" + searchValue + "%'";
                } else {
                    consult = consult + " AND (e.title like '%" + searchValue + "%' OR e.description like '%" + searchValue + "%')";
                }
            }
            SessionBean sessionBean = (SessionBean) SessionContext.getAttribute("sessionBean");
            if (sessionBean.getEjbSession().getCurrentArea() == null) {
                return ejbEventManager.listEventsSite(sessionBean.getEjbSession().getCurrentSite(), eventC, ejbEventCategorieManager.find(eventCategorieId), searchForDate, searchDate, consult);
            } else {
                return ejbEventManager.listEventsArea(sessionBean.getEjbSession().getCurrentArea(), eventC, ejbEventCategorieManager.find(eventCategorieId), searchForDate, searchDate, consult);
            }
        }
    }

    public String backView() {
        event = null;
        return "backEvent" + back;
    }

    public String backCreate() {
        SessionContext.removeAttribute("eventBean");
        return "back" + back;
    }

    public String backEdit() {
        SessionContext.removeAttribute("eventBean");
        return "back";
    }

    public String getEmail1() {
        return email1;
    }

    public void setEmail1(String email1) {
        this.email1 = email1;
    }

    public Date getToDay() {
        return new Date(System.currentTimeMillis());
    }

    public String getDescription() {
        try {
            if (event.getDescription().contains("\n")) {
                return event.getDescription().replaceAll("\n", "<br/>");
            } else {
                return event.getDescription().replaceAll("\r", "<br/>");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return "Do not Message";
        }
    }

    public String getSearchValue() {
        if(searchValue==null){
            try {
                PostBean postBean = (PostBean) RequestContext.getAttribute("postBean");
                searchValue = postBean.getSearchValue();
            } catch (Exception ex) {
            }
        }
        return searchValue;
    }

    public void setSearchValue(String searchValue) {
        this.searchValue = searchValue;
    }

    public boolean isOnlySearchTitles() {
        return onlySearchTitles;
    }

    public void setOnlySearchTitles(boolean onlySearchTitles) {
        this.onlySearchTitles = onlySearchTitles;
    }

    public boolean isHasImage() {
        return hasImage;
    }

    public void setHasImage(boolean hasImage) {
        this.hasImage = hasImage;
    }

    public int getPage() {
        if (page == 0) {
            page = 1;
        }
        return page;
    }

    public void setPage(int page) {
        this.page = page;
    }

    public Date getSearchDate() {
        if(searchDate==null){
            try {
                PostBean postBean = (PostBean) RequestContext.getAttribute("postBean");
                searchDate = postBean.getEventDate();
                searchForDate=postBean.isForDate();
            } catch (Exception ex) {
            }
        }
        return searchDate;
    }

    public void setSearchDate(Date searchDate) {
        this.searchDate = searchDate;
    }
    
    public boolean isSearchForDate() {
        return searchForDate;
    }

    public void setSearchForDate(boolean searchForDate) {
        this.searchForDate = searchForDate;
    }
    
    public int getContador(){
        try{
            return 20000-event.getDescription().length();
        }catch(Exception ex){
            return 20000;
        }
    }
    
    public void setContador(int contador){}

    public void flaggingMiscategorized(){
        try {
            event.setMiscategorized(ejbEventManager.merge(event).getMiscategorized()+1);
            ejbEventManager.update(event);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    
    public void flaggingProhibited(){
        try {
            event.setProhibited(ejbEventManager.merge(event).getProhibited()+1);
            ejbEventManager.update(event);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    
    public void flaggingSpam(){
        try {
            event.setSpam(ejbEventManager.merge(event).getSpam()+1);
            ejbEventManager.update(event);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    
    public void flaggingBest(){
        try {
            event.setBest(ejbEventManager.merge(event).getBest()+1);
            ejbEventManager.update(event);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
